﻿using Castle.Core.Configuration;
using Inovout.Runtime;
using System;
using System.Diagnostics;
using System.Reflection;

namespace Inovout.Test
{
    public class TestApplication : IApplication
    {
        private ApplicationWrapper applicationWrapper;
        private Assembly testAssembly;
        //public TestApplication()
        //    : this(GetTestApplicationAssembly())
        //{
        //}
        //private static Assembly GetTestApplicationAssembly()
        //{
        //    StackTrace st = new StackTrace();
        //    Type testType = null;
        //    foreach (var sf in st.GetFrames())
        //    {
        //        testType = sf.GetMethod().DeclaringType;
        //        if (Xunit.Sdk.TypeUtility.IsTestClass(Xunit.Sdk.Reflector.Wrap(testType)))
        //        {
        //            break;
        //        }
        //    }
        //    return testType.Assembly;
        //}
        public TestApplication(Assembly testAssembly)
        {
            this.testAssembly = testAssembly;
        }
        public void Run()
        {
            foreach (var assemblyName in testAssembly.GetReferencedAssemblies())
            {
                Assembly.Load(assemblyName);
            }
            Name = testAssembly.GetName().Name;
            //System.IO.FileStream fs= 
            //    new System.IO.FileStream(@"D:\storage.log",System.IO.FileMode.Append,  System.IO.FileAccess.Write);
            //byte[] buffer=System.Text.UTF8Encoding.UTF8.GetBytes(Name);
            //fs.Write(buffer,0,buffer.Length);
            //fs.Close();
            applicationWrapper = new ApplicationWrapper(this);
            applicationWrapper.Initialize();
        }

        public bool IsDebug
        {
            get
            {
#if DEBUG
                return true;
#else
                return false;
#endif
            }
        }

        public string Title
        {
            get { return applicationWrapper.Title; }
        }

        public string Name
        {
            get;
            private set;
        }

        public string Path
        {
            get { return Environment.CurrentDirectory; }
        }

        public IConfiguration Configuration
        {
            get { return applicationWrapper.Configuration; }
        }

        public DynamicDictionary Settings
        {
            get { return applicationWrapper.Settings; }
        }

        public void Dispose()
        {
            applicationWrapper.Dispose();
        }
    }
}
